package com.zy.springbootmybatis.controller.test1;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class ExcelReader {
    public static void main(String[] args) {
        String excelFilePath = "D:\\bb.xlsx";
        readExcel(excelFilePath);
    }

    public static void readExcel(String excelFilePath) {
        try (FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                for (Cell cell : row) { // 迭代每一列
                    // 根据不同数据类型，以字符串形式输出数据

                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            try {
                                FileWriter pw = new FileWriter("D://2.txt", true);
                                pw.write(cell.getStringCellValue());
                                pw.flush();
                                pw.close();
                            } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            try {
                                FileWriter pw = new FileWriter("D://2.txt", true);
                                pw.write(String.valueOf(cell.getNumericCellValue()));
                                pw.flush();
                                pw.close();
                            } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            System.out.print(cell.getCellFormula() + "\t");
                            break;
                        default: break;
                    }
                }
                System.out.println(); // 换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}